<template>
  <div class="common-list">
    <div class="title">
      <div style="flex:1; text-align: left;">{{ title }}</div>
      <div class="search">
        <SInput placeholder="搜索" icon="icon-search" value=""></SInput>
      </div>
    </div>
    <div class="obj-container">
      <div v-if="grouping">
        <ListContainer v-for="(group,index) in listData"
                       :key="index"
                       @select="onSelect"
                       @use="onUse"
                       :title="group.title"
                       :items="group.data"
        ></ListContainer>
      </div>
      <div v-else class="no-grouping">
        <ObjectItem
          v-for="(item, index) in listData"
          :key="index"
          :data="item"
          @click.prevent="onSelect(item)"
          @dblclick.stop="onUse(item)"
        ></ObjectItem>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, PropType } from 'vue';
import SInput from '@/ui-kit/input/input.vue';
import ListContainer from './list-container.vue';
import { ListGroup, ListItem } from './index';
import ObjectItem from './list-item.vue';

export default defineComponent({
  name: 'common-list',
  components: { ListContainer, SInput, ObjectItem },
  emits: ['select', 'use'],
  props: {
    title: {
      type: String,
      default: '',
    },
    grouping: {
      type: Boolean,
      default: true,
    },
    items: {
      type: Array as PropType<Array<ListItem>>,
      default: () => {
        return [];
      },
    },
  },
  setup(props, { emit }) {
    const listData = computed(() => {
      if (props.grouping) {
        const groups: ListGroup[] = [];
        props.items.forEach((item: ListItem) => {
          let groupItem = groups.find(el => el.title === item.group);
          if (!groupItem) {
            groupItem = { title: item.group, data: [] };
            groups.push(groupItem);
          }
          groupItem.data.push(item);
        });
        return groups;
      } else {
        return props.items;
      }
    });
    return {
      listData,
      onSelect(data: ListItem) {
        emit('select', data);
      },
      onUse(data: ListItem) {
        emit('use', data);
      },
    };
  },
});
</script>
<style scoped lang="scss">
.common-list {
  display: flex;
  flex-direction: column;

  .title {
    width: 100%;
    display: flex;
    flex-direction: row;
    align-content: center;
    justify-content: center;
  }

  .obj-container {
    box-sizing: border-box;
    padding: 5px;
    border: 1px solid #404040;
    width: 100%;
    overflow-y: auto;
    flex: 1;

    .no-grouping{
      display: flex;
      flex-direction: row;
      align-items: flex-start;
    }
  }
}
</style>
